package com.sy.service.impl;

import com.alibaba.excel.EasyExcel;
import com.sy.bean.pucharse.Purchase;
import com.sy.bean.pucharse.AuditStatus;
import com.sy.bean.pucharse.excel.PurchaseExcel;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.common.exception.BusinessException;
import com.sy.mapper.ContractMapper;
import com.sy.mapper.PurchaseDetailMapper;
import com.sy.mapper.PurchaseMapper;
import com.sy.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class PurchaseServiceImpl extends BaseServiceImpl<Purchase, PurchaseMapper> implements PurchaseService {
    String currentMaxCode; //当前最大编码 CG2024001
    @Autowired
    PurchaseDetailMapper purchaseDetailMapper;
    @Autowired
    ContractMapper contractMapper;
    @Autowired
    PurchaseMapper purchaseMapper;
    @Autowired
    HttpServletRequest request;

    @Transactional
    @Override
    public int save(Purchase entity) {
        entity.setCode(generateCode());
        //保存采购单
        int rs = super.save(entity);
        if (rs == 0)
            throw new BusinessException("保存采购单失败");
        //保存采购明细
        rs = purchaseDetailMapper.batchSave(entity.getId(), entity.getPurchaseDetailList());
        if (rs == 0)
            throw new BusinessException("保存采购单明细失败");
        //保存采购合同
        if (null != entity.getContracts() && entity.getContracts().size() > 0) {
            rs = contractMapper.batchSave(1, entity.getId(), entity.getContracts());
            if (rs == 0)
                throw new BusinessException("合同附件保存失败");
        }
        return 1;
    }

    @Transactional
    @Override
    public int update(Purchase entity) {
        //更新采购单
        int rs = baseMapper.update(entity);
        if (rs == 0)
            throw new BusinessException("更新采购单失败");
        //先删除之前的明细
        purchaseDetailMapper.deleteByPurchaseId(entity.getId());
        //生成明细
        rs = purchaseDetailMapper.batchSave(entity.getId(), entity.getPurchaseDetailList());
        if (rs == 0)
            throw new BusinessException("更新采购单失败");
        //先删除合同
        if (null != entity.getContracts() && entity.getContracts().size() > 0) {
            contractMapper.deleteBuPurchaseId(entity.getId(), 1);
            //更新合同
            rs = contractMapper.batchSave(1, entity.getId(), entity.getContracts());
            if (rs == 0)
                throw new BusinessException("更新合同失败");
        }
        return 1;
    }

    @Override
    public String exportPru(Map map) {
        List<PurchaseExcel> list = purchaseMapper.exportPru(map);
        String root = request.getServletContext().getRealPath("/") + "/excel";
        File file = new File(root);
        if (!file.exists())
            file.mkdirs();
        String newFileName = file.getAbsolutePath() + "/采购单列表.xlsx";
        EasyExcel.write(newFileName, PurchaseExcel.class)
                .sheet("采购单列表")
                .doWrite(() -> {
                    return list;
                });
        return "/excel/采购单列表.xlsx";
    }

    @Override
    public int batchDelete(List<Integer> ids) {
        return purchaseMapper.batchDelete(ids);
    }

    @Override
    public int batchStatus(AuditStatus status) {
        return purchaseMapper.batchStatus(status);
    }

    String generateCode() {
        String year = getYear();
        //判断当前最大编码是否存在
        if (null == currentMaxCode) {
            //如果不存在，查询当年最大编码
            currentMaxCode = baseMapper.queryMaxCode(year);
            if (null == currentMaxCode) {
                //说明不存在，生产第一个编码
                currentMaxCode = "CG" + year + "001";
            } else {
                //如果存在，新编码序号+1
                getNextCode();
            }
        } else {
            //如果存在，新编码序号+1
            getNextCode();
        }
        return currentMaxCode;
    }

    void getNextCode() {
        //CG2024001
        String prefix = currentMaxCode.substring(0, 6);
        String seq = currentMaxCode.substring(6);
        //转换数字001. tmp=1
        int tmp = Integer.parseInt(seq);
        tmp++;
        currentMaxCode = prefix + String.format("%03d", tmp);
    }

    String getYear() {
        LocalDate localDate = LocalDate.now();
        return String.valueOf(localDate.getYear());
    }
}
